<template>
  <div v-loading="loading" class="tab-container">
    <div v-if="subPageFlag==false">
      <!-- 查询与新增 -->
      <el-form ref="queryform" :model="queryform" :inline="true">
        <el-form-item>
          <el-select v-model="queryform.environment_id" placeholder="请选择环境" clearable @change="handleQuery()">
            <el-option v-for="item in environments" :key="item.id" :label="isSupper()?item.env_name+'【'+item.space_name+'】':item.env_name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model="queryform.project_id" filterable placeholder="搜索按项目查询" clearable class="wl-input" 
            @change="handleSelectProject()" @focus="handleFocusProject()" @keyup.native="handleInputProjectName">
            <el-option v-for="item in projects" :key="item.id" :label="item.name+'【'+item.environment_name+'】'" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item prop="user_id">
          <el-select v-model="queryform.user_id" filterable placeholder="搜索按用户查询" clearable class="wl-input" 
            @change="handleSelectUser()" @focus="handleFocusUsers()" @keyup.native="handleInputUserName">
            <el-option v-for="item in userlist" :key="item.user_id" :label="item.username" :value="item.user_id" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-input v-model="queryform.queryName" placeholder="请输入上线单名称" class="wl-input" @input="handleQuery()">
            <el-button slot="append" icon="el-icon-search" class="wl-search" @click="handleQuery()" />
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="queryform.user_id_me" :true-label="1" :false-label="0" @change="handleMy()">我的</el-checkbox>
        </el-form-item>
      </el-form>
      <el-form ref="queryform2" :model="queryform" :inline="true">
        <el-form-item>
          <el-radio-group v-model="queryform.status" class="wl-radio-group" @change="handleQuery()">
            <el-radio-button label="">所有</el-radio-button>
            <el-radio-button label="0">新建提交</el-radio-button>
            <el-radio-button label="1">审核通过</el-radio-button>
            <el-radio-button label="2">审核拒绝</el-radio-button>
            <el-radio-button label="3">上线中</el-radio-button>
            <el-radio-button label="4">上线完成</el-radio-button>
            <el-radio-button label="5">上线失败</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="enableCreate">
          <router-link :to="{name:'CreateTask', params:{flag:'create', context: queryContent()}}">
            <el-button type="primary" icon="el-icon-edit">新建上线单</el-button>
          </router-link>
        </el-form-item>
      </el-form>

      <!-- 列表 -->
      <el-table :data="list" :header-cell-style="{background:'#f4f4f5'}" class="wl-table">
        <el-table-column prop="id" :show-overflow-tooltip="true" label="ID" min-width="80">
          <template slot-scope="scope">
            <span style="margin-right:5px;">{{ scope.row.id }}</span>
            <el-popover v-if="scope.row.file_transmission_mode===2" placement="right" trigger="hover">
              <el-link v-for="(filename, index) in scope.row.file_list.split('\n')" :key="index" :underline="false" type="primary" style="display:block;cursor:default;">{{filename}}</el-link>
              <i slot="reference" class="el-icon-document-add" style="font-size:14px;" />
            </el-popover>
            <svg-icon v-if="scope.row.is_rollback===1" icon-class="resonse-rate" style="font-size:14px;-webkit-transform:rotateY(180deg);" />
          </template>
        </el-table-column>
        <el-table-column prop="name" :show-overflow-tooltip="true" label="上线单" min-width="180" />
        <el-table-column prop="project_name" :show-overflow-tooltip="true" label="项目" min-width="140" />
        <el-table-column prop="user_name" :show-overflow-tooltip="true" label="用户名" />
        <el-table-column prop="commit_id" :show-overflow-tooltip="true" label="版本" min-width="160">
          <template slot-scope="scope">
            <svg-icon v-if="scope.row.tag&&scope.row.tag!==''" icon-class="tag" class-name="wl-myicon wl-icon" />
            <svg-icon v-if="scope.row.branch&&scope.row.branch!==''" icon-class="branches" class-name="wl-myicon wl-icon" />
            <span v-if="scope.row.tag&&scope.row.tag!==''">{{ scope.row.tag }}</span>
            <span v-else><span>{{ scope.row.branch }}</span><span style="color:#97a8be;">#</span><span>{{ scope.row.commit_id }}</span></span>
          </template>
        </el-table-column>
        <el-table-column prop="environment_name" :show-overflow-tooltip="true" label="环境">
          <template slot-scope="scope">
            <span>{{ getEnviromentName(scope.row) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" min-width="80">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.status===4" type="success" size="mini">{{ getStatusDesc(scope.row.status) }}</el-tag>
            <el-tag v-else-if="scope.row.status===5" type="danger" size="mini">{{ getStatusDesc(scope.row.status) }}</el-tag>
            <el-tag v-else-if="scope.row.status===2" type="warning" size="mini">{{ getStatusDesc(scope.row.status) }}</el-tag>
            <el-tag v-else-if="scope.row.status===1" size="mini">{{ getStatusDesc(scope.row.status) }}</el-tag>
            <el-tag v-else type="info" size="mini">{{ getStatusDesc(scope.row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="updated_at" :show-overflow-tooltip="true" label="更新时间" min-width="135" />
        <el-table-column prop="operate" label="操作" min-width="165">
          <template slot-scope="scope">
            <el-button v-if="scope.row.enable_view&&scope.row.status!==3&&scope.row.status!==5" type="text">
              <router-link :to="{name:'ViewTask', params:{flag:'view', data:scope.row, context: queryContent()}}">
                <i class="el-icon-view wl-icon" />查看
              </router-link>
            </el-button>
            <el-popconfirm v-if="scope.row.enable_audit" confirm-button-text="通过" cancel-button-text="驳回" title="审核是否通过？" class="wl-icon" @onConfirm="handleAudit(scope.row)" @onCancel="handleReject(scope.row)">
              <el-button slot="reference" type="text" icon="el-icon-s-check" class="wl-table-icon">审核</el-button>
            </el-popconfirm>
            <el-button v-if="scope.row.enable_update" type="text" :class="((scope.row.enable_view&&scope.row.status!==3&&scope.row.status!==5)||scope.row.enable_audit)?'wl-deploy-edit':''">
              <router-link :to="{name:'CreateTask', params:{flag:'update', data:scope.row, context: queryContent()}}">
                <i class="el-icon-edit wl-icon" />编辑
              </router-link>
            </el-button>
            <el-button v-if="scope.row.enable_online" type="text">
              <router-link :to="{name:'ViewTask', params:{flag:'view', data:scope.row, context: queryContent()}}">
                <i class="el-icon-connection wl-icon" />上线
              </router-link>
            </el-button>
            <el-button v-if="scope.row.enable_rollback" type="text" icon="el-icon-refresh-left" class="wl-table-icon" @click="handleRollbackTask(scope.row)">回滚</el-button>
            <el-button v-if="scope.row.enable_delete" type="text" icon="el-icon-delete" class="wl-delete wl-table-icon" @click="handleDelete(scope.row)">删除</el-button>
            <el-dropdown v-if="scope.row.enable_deploy_to" class="wl-deploy-to" @command="handleDeployTo">
              <span class="el-dropdown-link"><i class="el-icon-arrow-down el-icon--right wl-icon"></i>发至</span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item v-for="(prj, index) in scope.row.deploy_to_list" :key="prj.project_id" 
                  :command="beforehandleDeployTo(scope.row, prj, index)">{{prj.environment_name}}
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="wl-pagination"
        background
        layout="total, sizes, prev, pager, next"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100, 150, 200]"
        :page-size="pageSize"
        :total="count"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 子菜单路由 -->
    <router-view />
  </div>
</template>

<script>
import { getTasks, auditTask, rejectTask, deleteTask, rollbackTask } from '@/api/task'
import { getEnvironment } from '@/api/env'
import { getSpaceMembers } from '@/api/space'
import { getProjects } from '@/api/project'

export default {
  name: 'WalleDeploy',
  data() {
    return {
      loading: false,
      subPageFlag: false, // 当打开子菜单时，当前页内屏蔽
      queryform: {
        queryName: '',
        environment_id: '',
        project_id: '',
        user_id: '',
        status: '',
        user_id_me: false
      },
      environments: [],
      projects:[],
      userlist: [],
      enableCreate: false,
      list: [],
      count: 0,
      pageSize: 10,
      currentPage: 1
    }
  },
  mounted() {
    if (this.$route.name === 'WalleDeploy') {
      const params = this.$route.params
      this.subPageFlag = false
      if (params && params.currentPage) {
        this.currentPage = params.currentPage
        this.pageSize = params.pageSize
        this.queryform.queryName = params.queryName
        this.queryform.environment_id = params.environment_id
        this.queryform.project_id = params.project_id
        this.queryform.user_id = params.user_id
        this.queryform.user_id_me = params.user_id_me
        this.queryform.status = params.status
      }
      if (this.queryform.user_id) {
        this.getUserList(200)
      }
      if (this.queryform.project_id) {
        this.getProjectList(100)
      }
      this.getEnviroments()
      this.getTasks()
    } else {
      this.subPageFlag = true
    }
  },
  methods: {
    isSupper: function() { // 判断是超级用户
      const user = this.$store.getters.user
      return user.role === 'SUPER'
    },
    queryContent() {
      return {
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        queryName: this.queryform.queryName,
        environment_id: this.queryform.environment_id,
        project_id: this.queryform.project_id,
        user_id: this.queryform.user_id,
        user_id_me: this.queryform.user_id_me,
        status: this.queryform.status
      }
    },
    handleQuery(event) { // 查询
      this.getTasks()
    },
    handleSizeChange(pageSize) { // 设置分页大小事件
      this.pageSize = pageSize
      this.handleQuery()
    },
    handleCurrentChange(pageno) { // 处理分页事件
      this.currentPage = pageno
      this.handleQuery()
    },
    handleSelectProject() {
      this.handleQuery()
    },
    handleFocusProject() {
      this.getProjectList(100)
    },
    handleInputProjectName(e) {
      this.getProjectList(100, 1, e.target.value.trim())
    },
    handleSelectUser() {
      this.queryform.user_id_me = false
      this.handleQuery()
    },
    handleFocusUsers() {
      this.getUserList(200)
    },
    handleInputUserName(e) {
      this.getUserList(200, 1, e.target.value.trim())
    },
    handleMy() {
      this.queryform.user_id = ''
      this.handleQuery()
    },
    handleAudit(row) { // 审核通过
      this.loading = true
      auditTask(row.id).then(response => {
        this.loading = false
        if (!response.data || response.data.code !== 0) {
          this.$message({ type: 'error', message: (response.data && response.data.message) ? response.data.message : '请求数据异常！' })
          return
        }
        this.$message({ type: 'success', message: '审核通过！' })
        this.handleQuery()
      }).catch(error => {
        this.loading = false
        this.$message({ type: 'error', message: '请求异常！' })
        console.log(error)
      })
    },
    handleReject(row) { // 审核拒绝
      this.loading = true
      rejectTask(row.id).then(response => {
        this.loading = false
        if (!response.data || response.data.code !== 0) {
          this.$message({ type: 'error', message: (response.data && response.data.message) ? response.data.message : '请求数据异常！' })
          return
        }
        this.$message({ type: 'success', message: '审核驳回！' })
        this.handleQuery()
      }).catch(error => {
        this.loading = false
        this.$message({ type: 'error', message: '请求异常！' })
        console.log(error)
      })
    },
    handleDelete(row) { // 删除
      this.$confirm('确定删除上线单【' + row.name + '】吗? ', '提示', { type: 'warning', confirmButtonText: '确定', cancelButtonText: '取消' }).then(() => {
        this.loading = true
        deleteTask(row.id).then(response => {
          this.loading = false
          if (!response.data || response.data.code !== 0) {
            this.$message({ type: 'error', message: (response.data && response.data.message) ? response.data.message : '请求数据异常！' })
            return
          }
          this.handleQuery()
          this.$message({ type: 'success', message: '删除成功！' })
        }).catch(error => {
          this.loading = false
          this.$message({ type: 'error', message: '删除失败!' })
        })
      }).catch(error => {
        this.$message({ type: 'info', message: '已取消删除!' })
      })
    },
    handleRollbackTask(row) { // 回滚
      this.$confirm('确定回滚上线单【' + row.name + '】吗? ', '提示', { type: 'warning', confirmButtonText: '确定', cancelButtonText: '取消' }).then(() => {
        this.loading = true
        rollbackTask(row.id).then(response => {
          this.loading = false
          if (!response.data || response.data.code !== 0) {
            this.$message({ type: 'error', message: (response.data && response.data.message) ? response.data.message : '请求数据异常！' })
            return
          }
          this.handleQuery()
          this.$message({ type: 'success', message: '回滚成功，请打开回滚单进行上线！' })
        }).catch(error => {
          this.loading = false
          this.$message({ type: 'error', message: '回滚失败!' })
        })
      }).catch(error => {
        this.$message({ type: 'info', message: '已取消回滚!' })
      })
    },
    beforehandleDeployTo(row, project, command) {
      return {
          'task': row,
          'project': project,
          'command': command
      }
    },
    handleDeployTo(command) { // 上线成功任务单发至其他环境
      this.$router.push({
        name:'CreateTask', 
        params:{
          flag: 'create', 
          data: command.task,
          project: command.project,
          context: this.queryContent()
        }
      })
    },
    getProjectList(size, page, query) { // 获取项目列表
      this.projects = []
      getProjects(30, 1, query, this.queryform.environment_id).then(response => {
        this.loading = false
        if (!response.data || response.data.code !== 0) {
          this.$message({ type: 'error', message: (response.data && response.data.message) ? response.data.message : '请求数据异常！' })
          return
        }
        this.projects = response.data.data.list
      }).catch(error => {
        this.loading = false
        this.$message({ type: 'error', message: '请求失败!' })
      })
    },
    getUserList(size, page, query) { // 获取可以添加到项目的用户
      this.userlist = []
      const space = this.$store.getters.space
      getSpaceMembers(space.current.id, size, page, query).then(response => {
        if (!response.data || response.data.code !== 0) {
          this.$message({ type: 'error', message: (response.data && response.data.message) ? response.data.message : '请求数据异常！' })
          return
        }
        const data = response.data.data
        this.userlist = data.list
      }).catch(error => {
        this.$message({ type: 'error', message: '请求异常！' })
        console.log(error)
      })
    },
    getEnviroments() {
      getEnvironment().then(response => {
        if (!response.data || response.data.code !== 0) {
          this.$message({ type: 'error', message: (response.data && response.data.message) ? response.data.message : '请求数据异常！' })
          return
        }
        const data = response.data.data
        this.environments = data.list
      }).catch(error => {
        this.$message({ type: 'error', message: '请求异常！' })
        console.log(error)
      })
    },
    getTasks() {
      this.loading = true
      const kw = this.queryform.queryName.trim()
      const userid = this.queryform.user_id_me ? this.$store.getters.user.id : this.queryform.user_id
      const environment_id = this.queryform.environment_id
      const project_id = this.queryform.project_id
      const status = this.queryform.status
      getTasks(this.pageSize, this.currentPage, kw, userid, environment_id, project_id, status).then(response => {
        this.loading = false
        if (!response.data || response.data.code !== 0) {
          this.$message({ type: 'error', message: (response.data && response.data.message) ? response.data.message : '请求数据异常！' })
          return
        }
        const data = response.data.data
        this.enableCreate = data.enable_create
        this.count = data.count
        this.list = data.list
        if (this.count > 0 && this.list.length == 0) { // 调整PageNo
          this.currentPage = Math.ceil(this.count / this.pageSize)
          this.getTasks()
        }
      }).catch(error => {
        this.loading = false
        this.$message({ type: 'error', message: '请求异常！' })
        console.log(error)
      })
    },
    getDeployVersion(row) {
      return (row.tag && row.tag !== '') ? row.tag : row.branch + '#' + row.commit_id
    },
    getEnviromentName(row) {
      if (this.isSupper()) {
        for (let i in this.environments) {
          if (this.environments[i].id === row.environment_id) {
            return this.environments[i].env_name + '【'+this.environments[i].space_name + '】'
          }
        }
      }
      return row.environment_name
    },
    getStatusDesc(status) { // 上线单状态
      switch (status) {
        case 0: return '新建提交'
        case 1: return '审核通过'
        case 2: return '审核拒绝'
        case 3: return '上线中'
        case 4: return '上线完成'
        case 5: return '上线失败'
        default: return ''
      }
    }
  }
}
</script>

<style scoped>
  .tab-container {
    margin: 20px;
  }
  .wl-table {
    width:100%;
    margin-top: 10px;
  }
  .wl-icon {
    margin-right: 2px;
  }
  .wl-operate {
    overflow: hidden;
  }
  .wl-input {
    width: 200px;
  }
  .wl-form-input {
    width: 360px;
  }
  .wl-search {
    background: #f5f7fa;
  }
  .wl-deploy-edit {
    padding-left: 10px;
  }
  .wl-deploy-to {
    padding-left: 8px;
  }
  .wl-delete {
    color: #f56c6c;
  }
  .wl-pagination {
    margin-top:10px;
  }
  .wl-myicon {
    font-size: 14px;
  }
  .wl-table-icon >>> span {
    margin-left: 2px;
  }
  .wl-radio-group >>> .el-radio-button__orig-radio:checked + .el-radio-button__inner {
    background-color: #f5f7fa;
    border-color: #DCDFE6;
    -webkit-box-shadow: -1px 0 0 0 #DCDFE6;
    box-shadow: -1px 0 0 0 #DCDFE6;
  }
  .wl-radio-group >>> .el-radio-button__inner {
    color: #606266;
  }
  .el-dropdown-link {
    cursor: pointer;
    color: #409EFF;
    font-size: 12px;
  }
  .el-icon-arrow-down {
    font-size: 12px;
  }
</style>
